<template>
  <view class="refund-apply-page" :style="{
    '--primary-color': themeColorStyles.primaryColor,
    '--primary-color-bg': themeColorStyles.primaryColorBg,
    '--primary-color-border': themeColorStyles.primaryColorBorder
  }">


    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <scroll-view class="content-scroll" scroll-y v-else>
      <!-- 订单信息卡片 -->
      <view class="order-info-card">
        <view class="card-header">
          <text class="card-title">订单信息</text>
        </view>
        <view class="order-content">
          <view class="order-item">
            <text class="label">订单号：</text>
            <text class="value">{{ orderInfo.orderNo }}</text>
          </view>
          <view class="order-item">
            <text class="label">订单金额：</text>
            <text class="value amount">¥{{ orderInfo.totalAmount }}</text>
          </view>
          <view class="order-item">
            <text class="label">下单时间：</text>
            <text class="value">{{ orderInfo.createTime }}</text>
          </view>
        </view>
      </view>

      <!-- 退款表单 -->
      <view class="refund-form-card">
        <view class="card-header">
          <text class="card-title">退款信息</text>
        </view>
        <view class="form-content">
          <!-- 退款类型 -->
          <view class="form-item">
            <text class="form-label">退款类型</text>
            <view class="radio-group">
              <view 
                class="radio-item" 
                v-for="type in refundTypes" 
                :key="type.value"
                @click="selectRefundType(type.value)"
              >
                <view class="radio-icon" :class="{ active: refundForm.refundType === type.value }">
                  <text class="radio-dot" v-if="refundForm.refundType === type.value"></text>
                </view>
                <text class="radio-text">{{ type.label }}</text>
              </view>
            </view>
          </view>

          <!-- 退款原因 -->
          <view class="form-item">
            <text class="form-label">退款原因</text>
            <view class="reason-list">
              <view 
                class="reason-item" 
                v-for="reason in refundReasons" 
                :key="reason"
                :class="{ active: refundForm.refundReason === reason }"
                @click="selectReason(reason)"
              >
                <text class="reason-text">{{ reason }}</text>
                <text class="check-icon" v-if="refundForm.refundReason === reason">✓</text>
              </view>
            </view>
          </view>

          <!-- 退款金额 -->
          <view class="form-item">
            <text class="form-label">退款金额</text>
            <view class="amount-input">
              <text class="currency">¥</text>
              <input 
                class="amount-value" 
                type="digit" 
                v-model="refundForm.refundAmount" 
                placeholder="请输入退款金额"
                :disabled="isViewMode"
              />
            </view>
            <text class="amount-tip">最多可退款 ¥{{ orderInfo.totalAmount }}</text>
          </view>

          <!-- 退款说明 -->
          <view class="form-item">
            <text class="form-label">退款说明</text>
            <textarea 
              class="textarea-input" 
              v-model="refundForm.handleNote" 
              placeholder="请详细说明退款原因（选填）"
              maxlength="200"
              :disabled="isViewMode"
            ></textarea>
            <text class="char-count">{{ refundForm.handleNote ? refundForm.handleNote.length : 0 }}/200</text>
          </view>

          <!-- 上传凭证 -->
          <view class="form-item">
            <text class="form-label">上传凭证</text>
            <view class="upload-area">
              <view class="image-list">
                <view 
                  class="image-item" 
                  v-for="(image, index) in evidenceImages" 
                  :key="index"
                >
                  <image class="evidence-image" :src="image.url" mode="aspectFill" />
                  <view class="delete-btn" @click="deleteImage(index)" v-if="!isViewMode">
                    <text class="delete-icon">×</text>
                  </view>
                </view>
                <view class="upload-btn" @click="chooseImage" v-if="evidenceImages.length < 3 && !isViewMode">
                  <text class="upload-icon">+</text>
                  <text class="upload-text">上传图片</text>
                </view>
              </view>
              <text class="upload-tip">最多上传3张图片，支持jpg、png格式</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 退款状态显示（查看模式） -->
      <view class="status-card" v-if="isViewMode && refundInfo">
        <view class="card-header">
          <text class="card-title">退款状态</text>
        </view>
        <view class="status-content">
          <view class="status-item">
            <text class="status-label">当前状态：</text>
            <text class="status-value" :class="statusClass">{{ getStatusText(refundInfo.refundStatus) }}</text>
          </view>
          <view class="status-item" v-if="refundInfo.applyTime">
            <text class="status-label">申请时间：</text>
            <text class="status-value">{{ refundInfo.applyTime }}</text>
          </view>
          <view class="status-item" v-if="refundInfo.handleTime">
            <text class="status-label">处理时间：</text>
            <text class="status-value">{{ refundInfo.handleTime }}</text>
          </view>
          <view class="status-item" v-if="refundInfo.handleNote">
            <text class="status-label">处理备注：</text>
            <text class="status-value">{{ refundInfo.handleNote }}</text>
          </view>
        </view>
      </view>

      <!-- 底部间距 -->
      <view class="bottom-space"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="footer-actions" v-if="!isViewMode">
      <view class="action-buttons">
        <view class="action-btn secondary" @click="goBack" :style="{background: themeColorStyles.primaryColorBg, border: `2rpx solid ${themeColorStyles.primaryColor}`}">
          <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">取消</text>
        </view>
        <view class="action-btn primary" @click="submitRefund" :class="{ disabled: submitting }" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
          <text class="btn-text">{{ submitting ? '提交中...' : '提交申请' }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserOrder } from '@/api/order'
import { applyRefund, getRefundStatus } from '@/api/order'
import upload from '@/utils/upload'
import { API_CONFIG } from '@/api/config'
import { checkLoginStatus, handleApiError } from '@/utils/loginCheck'
import { getUserInfo } from '@/utils/auth'
import { getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/theme'
import themeColorMixin from '@/mixins/themeColorMixin'

export default {
  mixins: [themeColorMixin],
  data() {
    return {
      loading: true,
      submitting: false,
      isViewMode: false, // 是否为查看模式
      orderId: '',
      orderNo: '',
      orderInfo: {},
      refundInfo: null, // 已存在的退款信息
      refundForm: {
        orderNo: '',
        refundType: '1', // 1仅退款 2退货退款 3换货
        refundReason: '',
        refundAmount: '',
        handleNote: ''
      },
      evidenceImages: [],
      refundTypes: [
        { value: '1', label: '仅退款' },
        { value: '2', label: '退货退款' }
      ],
      refundReasons: [
        '买错了',
        '重复下单',
        '尺码不合适',
        '商品描述不符',
        '商品质量问题',
        '商品有异味',
        '不喜欢颜色',
        '商品有划痕',
        '商品损坏',
        '价格变动',
        '发错货',
        '其他原因'
      ]
    }
  },
  
  async onLoad(options) {
    await this.initThemeColor()
    
    if (options.orderId) {
      this.orderId = options.orderId
    }
    if (options.orderNo) {
      this.orderNo = options.orderNo
      this.refundForm.orderNo = options.orderNo
    }
    
    this.initPage()
  },
  computed: {
    statusClass() {
      if (!this.refundInfo || !this.refundInfo.refundStatus) {
        return ''
      }
      const classMap = {
        '1': 'pending',
        '2': 'approved',
        '3': 'rejected',
        '4': 'processing',
        '5': 'success',
        '6': 'failed'
      }
      return classMap[this.refundInfo.refundStatus] || ''
    }
  },
  methods: {
    // 初始化页面
    async initPage() {
      try {
        // 使用统一的登录检测
        const loginResult = await checkLoginStatus()
        if (!loginResult.isLoggedIn) {
          this.loading = false
          return
        }
        
        // 获取订单信息
        if (this.orderId) {
          await this.getOrderInfo()
        }
        
        // 检查是否已有退款申请
        if (this.orderNo) {
          await this.checkExistingRefund()
        }
        
      } catch (error) {
        console.error('初始化页面失败:', error)
        // 使用统一的错误处理
        handleApiError(error, {
          showToast: true,
          autoRedirect: false,
          autoWechatLogin: false
        })
      } finally {
        this.loading = false
      }
    },
    
    // 获取订单信息
    async getOrderInfo() {
      try {
        // 获取用户信息
        const userInfo = await getUserInfo()
        const response = await getUserOrder(this.orderId, userInfo.userId)
        if (response.code === 200 && response.data) {
          this.orderInfo = response.data
          this.orderNo = this.orderInfo.orderNo
          this.refundForm.orderNo = this.orderInfo.orderNo
          this.refundForm.refundAmount = this.orderInfo.paymentAmount || this.orderInfo.totalAmount
        }
      } catch (error) {
        console.error('获取订单信息失败:', error)
        throw error
      }
    },
    
    // 检查已存在的退款申请
    async checkExistingRefund() {
      try {
        const response = await getRefundStatus(this.orderNo)
        if (response.code === 200 && response.data) {
          // 已有退款申请，切换到查看模式
          this.refundInfo = response.data
          this.isViewMode = true
          
          // 填充表单数据（只读）
          this.refundForm.refundType = response.data.refundType
          this.refundForm.refundReason = response.data.refundReason
          this.refundForm.refundAmount = response.data.refundAmount
          this.refundForm.handleNote = response.data.handleNote || ''
          
          // 处理凭证图片
          if (response.data.evidenceImages) {
            this.evidenceImages = response.data.evidenceImages.split(',').map(imagePath => {
              const fullUrl = imagePath.startsWith('http') ? imagePath : `${API_CONFIG.SERVER_RUOYI_IP}${imagePath}`
              return {
                url: fullUrl,
                isLocal: false,
                serverPath: imagePath
              }
            })
          }
        }
      } catch (error) {
        console.error('检查退款状态失败:', error)
      }
    },
    
    // 选择退款类型
    selectRefundType(type) {
      if (!this.isViewMode) {
        this.refundForm.refundType = type
      }
    },
    
    // 选择退款原因
    selectReason(reason) {
      if (!this.isViewMode) {
        this.refundForm.refundReason = reason
      }
    },
    
    // 选择图片
    chooseImage() {
      if (this.isViewMode) return
      
      uni.chooseImage({
        count: 3 - this.evidenceImages.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 将选择的图片添加到列表中，使用本地路径显示
          res.tempFilePaths.forEach(tempPath => {
            this.evidenceImages.push({
              url: tempPath, // 本地临时路径，用于显示
              isLocal: true, // 标记为本地图片
              serverPath: null // 服务器路径，提交时上传后设置
            })
          })
        }
      })
    },

    // 批量上传图片到服务器（提交时调用）
    async uploadImagesToServer() {
      const localImages = this.evidenceImages.filter(img => img.isLocal && !img.serverPath)
      
      if (localImages.length === 0) {
        return // 没有需要上传的本地图片
      }
      
      uni.showLoading({
        title: '上传图片中...'
      })
      
      try {
        for (let i = 0; i < localImages.length; i++) {
          const serverPath = await this.uploadSingleImage(localImages[i].url)
          localImages[i].serverPath = serverPath
          localImages[i].isLocal = false
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        throw new Error('图片上传失败，请重试')
      } finally {
        uni.hideLoading()
      }
    },

    // 上传单个图片
    async uploadSingleImage(filePath) {
      try {
        const response = await upload({
          url: '/common/upload',
          filePath: filePath,
          name: 'file'
        });
        
        if (response.code === 200) {
          return response.fileName; // 返回服务器返回的文件名
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('上传图片失败:', error);
        throw error;
      }
    },
    
    // 删除图片
    deleteImage(index) {
      if (this.isViewMode) return
      this.evidenceImages.splice(index, 1)
    },
    
    // 提交退款申请
    async submitRefund() {
      if (this.submitting || this.isViewMode) return
      
      // 表单验证
      if (!this.refundForm.refundType) {
        uni.showToast({
          title: '请选择退款类型',
          icon: 'none'
        })
        return
      }
      
      if (!this.refundForm.refundReason) {
        uni.showToast({
          title: '请选择退款原因',
          icon: 'none'
        })
        return
      }
      
      if (!this.refundForm.refundAmount || parseFloat(this.refundForm.refundAmount) <= 0) {
        uni.showToast({
          title: '请输入正确的退款金额',
          icon: 'none'
        })
        return
      }
      
      if (parseFloat(this.refundForm.refundAmount) > parseFloat(this.orderInfo.totalAmount)) {
        uni.showToast({
          title: '退款金额不能超过订单金额',
          icon: 'none'
        })
        return
      }
      
      this.submitting = true
      
      try {
        // 先上传本地图片到服务器
        await this.uploadImagesToServer()
        
        // 准备提交数据
        const submitData = {
          ...this.refundForm,
          evidenceImages: this.evidenceImages.map(img => img.serverPath || img.url).join(',') // 使用服务器路径
        }
        
        const response = await applyRefund(submitData)
        
        if (response.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: response.msg || '提交失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        console.error('提交退款申请失败:', error)
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '1': '待审核',
        '2': '审核通过',
        '3': '审核拒绝',
        '4': '退款中',
        '5': '退款成功',
        '6': '退款失败'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 获取状态样式类

    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.refund-apply-page {
  background: linear-gradient(180deg, #F8FAFE 0%, #F2F6FC 100%);
  min-height: 100vh;
  padding-bottom: 120rpx;
}



/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #E8F2FF;
  border-top: 4rpx solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 24rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 内容滚动区域 */
.content-scroll {
  height: calc(100vh - 120rpx);
  padding: 32rpx;
}

/* 卡片基础样式 */
.order-info-card,
.refund-form-card,
.status-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
  border: 1px solid var(--primary-color-border, rgba(74, 144, 226, 0.08));
}

.card-header {
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 1px solid #F5F7FA;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

/* 订单信息 */
.order-content {
  padding: 32rpx;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #1A1A1A;
  
  &.amount {
    color: var(--primary-color, #4A90E2);
    font-weight: 600;
  }
}

/* 表单内容 */
.form-content {
  padding: 32rpx;
}

.form-item {
  margin-bottom: 48rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 24rpx;
}

/* 单选组 */
.radio-group {
  display: flex;
  gap: 32rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  border-radius: 12rpx;
  background: #F8FAFE;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
  }
}

.radio-icon {
  width: 36rpx;
  height: 36rpx;
  border: 2rpx solid #D1D5DB;
  border-radius: 50%;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  
  &.active {
    border-color: var(--primary-color, #4A90E2);
    background: var(--primary-color-bg, #F0F7FF);
  }
}

.radio-dot {
  width: 12rpx;
  height: 12rpx;
  background: #FFFFFF;
  border-radius: 50%;
}

.radio-text {
  font-size: 28rpx;
  color: #1A1A1A;
}

/* 原因列表 */
.reason-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.reason-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  border: 2rpx solid #E5E7EB;
  border-radius: 16rpx;
  background: #FFFFFF;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &.active {
    border-color: var(--primary-color, #4A90E2);
    background: var(--primary-color-bg, rgba(74, 144, 226, 0.05));
    box-shadow: 0 4rpx 20rpx var(--primary-color-border, rgba(74, 144, 226, 0.1));
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.reason-text {
  font-size: 28rpx;
  color: #1A1A1A;
}

.reason-item.active .reason-text {
  color: var(--primary-color, #4A90E2);
  font-weight: 500;
}

.check-icon {
  font-size: 32rpx;
  color: var(--primary-color, #4A90E2);
  font-weight: 600;
}

/* 金额输入 */
.amount-input {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border: 1px solid #E5E7EB;
  border-radius: 16rpx;
  background: #FFFFFF;
}

.currency {
  font-size: 32rpx;
  color: #1A1A1A;
  margin-right: 16rpx;
}

.amount-value {
  flex: 1;
  font-size: 32rpx;
  color: #1A1A1A;
  border: none;
  outline: none;
}

.amount-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
}

/* 文本域 */
.textarea-input {
  width: 100%;
  min-height: 200rpx;
  padding: 24rpx;
  border: 1px solid #E5E7EB;
  border-radius: 16rpx;
  background: #FFFFFF;
  font-size: 28rpx;
  color: #1A1A1A;
  line-height: 1.5;
  resize: none;
  outline: none;
}

.char-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  margin-top: 12rpx;
}

/* 上传区域 */
.upload-area {
  
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.evidence-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  font-size: 32rpx;
  color: #FFFFFF;
  font-weight: 600;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #D1D5DB;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #F9FAFB;
  transition: all 0.3s ease;
  
  &:active {
    background: #F3F4F6;
    transform: scale(0.98);
  }
}

.upload-icon {
  font-size: 48rpx;
  color: #9CA3AF;
  margin-bottom: 8rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #9CA3AF;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
}

/* 状态内容 */
.status-content {
  padding: 32rpx;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.status-label {
  font-size: 28rpx;
  color: #666;
  min-width: 160rpx;
}

.status-value {
  flex: 1;
  font-size: 28rpx;
  color: #1A1A1A;
  text-align: right;
  
  &.pending {
    color: #F59E0B;
  }
  
  &.approved {
    color: #10B981;
  }
  
  &.rejected {
    color: #EF4444;
  }
  
  &.processing {
    color: #3B82F6;
  }
  
  &.success {
    color: #10B981;
  }
  
  &.failed {
    color: #EF4444;
  }
}

/* 底部操作栏 */
.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #FFFFFF;
  padding: 32rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
  border-top: 1px solid rgba(74, 144, 226, 0.08);
}

.action-buttons {
  display: flex;
  gap: 24rpx;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  
  &.secondary {
    &:active {
      transform: scale(0.98);
    }
  }
  
  &.primary {
    .btn-text {
      color: #FFFFFF;
    }
    
    &:active {
      transform: scale(0.98);
    }
    
    &.disabled {
      opacity: 0.6;
      pointer-events: none;
    }
  }
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
}

.bottom-space {
  height: 120rpx;
}
</style>